import datetime

from django.http import HttpResponse
from django.shortcuts import render, redirect, reverse

from user.models import UserModel


# Create user views here.


def index(request):
    """ 首页 """

    # 获取cookie
    userid = request.COOKIES.get('userid', 0)  # 如果不存在，给个默认值

    # 查询当前登录用户
    user = UserModel.objects.filter(id=userid).first()

    return render(request, 'index.html', {'user': user})


def register(request):
    """ 注册 """
    if request.method == 'GET':
        return render(request, 'register.html')

    elif request.method == 'POST':
        # 接收前端提交过来的数据
        uname = request.POST.get('uname')
        passwd = request.POST.get('passwd')
        age = request.POST.get('age')

        # CSRF verification failed. Request aborted.有两种解决方法：
        # 1. 注释掉CSRF中间件
        # 2. 在前端form表单的第一行代码处加上{% csrf_token %}

        # 先判断用户是否已经被注册过
        users = UserModel.objects.filter(username=uname)
        if users.exists():
            return HttpResponse('用户名已存在！')
        # 实现注册功能
        try:
            user = UserModel()
            user.username = uname
            user.password = passwd
            user.age = age
            user.save()
        except:
            return HttpResponse('注册失败！')

        print(uname, passwd, age)

        return redirect(reverse('login'))


def login(request):
    """ 登录 """

    if request.method == 'GET':

        return render(request, 'login.html')

    elif request.method == 'POST':
        # 接收前端传过来的表单
        uname = request.POST.get('uname')
        passwd = request.POST.get('passwd')

        # 登录验证
        users = UserModel.objects.filter(username=uname, password=passwd)  # 用户名存在且密码正确
        if users.exists():
            # 后去当前登录用户对象
            user = users.first()
            # 设置cookie
            """
            1. cookie存储在浏览器本地
            2. cookie不能跨域，不能跨浏览器
            3. cookie存储的内容是字符串，不能为中文，一般存储大小不要超过4KB
            4. cookie由后端创建返回前端保管
            """
            response = redirect(reverse('index'))
            # response.set_cookie('userid', user.id)  # 创建cookie
            # 设置过期时间：
            response.set_cookie('userid', user.id, max_age=7*24*3600)  # max_age单位秒
            response.set_cookie('userid', user.id, expires=datetime.datetime(2024, 12, 30, 10, 10))  # expires过期的日期
            response.set_cookie('userid', user.id, expires=datetime.datetime.now()+datetime.timedelta(days=10))  # expires过期的日期


            # 验证成功后，跳转到登录页面
            return response

        else:
            return HttpResponse('账号密码错误！')


def logout(request):
    """ 注销 """

    response = redirect(reverse('index'))

    response.delete_cookie('userid')  # 删除指定cookie

    return response
